package com.bobo.base.utils;/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


import android.content.Context;

import com.bobo.base.bean.UserInfoBean;
import com.google.gson.Gson;

/**
 * Token管理工具
 *
 * @author xuexiang
 * @since 2019-11-17 22:37
 */
public final class TokenUtils {

    private static String sToken;

    private static final String KEY_TOKEN = "TOKEN";
    private static final String USER_INFO = "USER_INFO";
    private static final String SAVE_SHOPENTER = "SAVE_SHOPENTER";
    private static final String SAVE_SHOPENTER_NATIVE = "SAVE_SHOPENTER_NATIVE";
    private static final String DEFUAT_AREA = "DEFUAT_AREA";


    private TokenUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }


    /**
     * 初始化Token信息
     */
    public static void init(Context context) {
        MMKVUtils.init(context);
        sToken = MMKVUtils.getString(KEY_TOKEN, "");
    }

    public static void setToken(String token) {
        sToken = token;
        MMKVUtils.put(KEY_TOKEN, token);
    }

    public static void clearToken() {
        sToken = null;
        MMKVUtils.remove(KEY_TOKEN);
        MMKVUtils.remove("choseShopCode");//清除彩票收款码中切换店铺的下标
        clearUserInfo();
    }

    public static String getToken() {
        return sToken;
    }

    public static boolean hasToken() {
        return MMKVUtils.containsKey(KEY_TOKEN);
    }

    public static void setUserInfo(String userInfo) {
        MMKVUtils.put(USER_INFO, userInfo);
    }

    public static UserInfoBean getUserInfo() {
        return new Gson().fromJson(MMKVUtils.getString(USER_INFO, ""),UserInfoBean.class);

    }

    public static void clearUserInfo() {
        MMKVUtils.remove(USER_INFO);
    }



    /**
     * 处理登录成功的事件
     *
     * @param token 账户信息
     */
    public static boolean handleLoginSuccess(String token) {
        if (!StringUtils.isEmpty(token)) {
            XToastUtils.toast("登录成功！");
            setToken(token);
            return true;
        } else {
            XToastUtils.toast("登录失败！");
            return false;
        }
    }

    /**
     * 处理登出的事件
     */
    public static void handleLogoutSuccess() {
        //登出时，清除账号信息
        clearToken();
        XToastUtils.toast("登出成功！");
    }

}
